# Create your views here.
import qrcode
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.six import BytesIO

from cmdb import models

user_list = [
    {"user": "huan", "pwd": "123"},
    {"user": "jin", "pwd": "456"},
]


def index(request):
    if request.method == "POST":
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        # 添加到数据库
        if username != '':
            models.UserInfo.objects.create(user=username, pwd=password)
    #     读取所有数据
    user_list = models.UserInfo.objects.all()
    # render返回的是页面
    # HttpResponse返回的是字符串
    return render(request, "index.html", {"data": user_list})


def userData(request):
    user_info_objects_all = models.UserInfo.objects.all()
    return HttpResponse(user_info_objects_all)


def get_qrcode(request):
    img = qrcode.make(request.GET.get('data'))
    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    return HttpResponse(image_stream, content_type="image/png")
